package com.inibb.app.util.upload;

import java.io.File;
import java.util.Properties;

public class FileSizeValidationHandler implements FileHandler{
	private Properties fileConfig;
	
	public FileSizeValidationHandler(Properties fileConfig) {
		super();
		this.fileConfig = fileConfig;
	}

	public ValidationResult handle(File file) {
		long lminSize=getSize("system.upload.minFileSize");
		long lmaxSize=getSize("system.upload.maxFileSize");
		long fsize=file.length();
		ValidationResult vr=new ValidationResult();
		if(fsize<lminSize){
			vr.getErrors().put(file.getName(), "The file is too small") ;
		 }else if(fsize>lmaxSize){
			 vr.getErrors().put(file.getName(), "The file is too larger");
		 }
		
		return vr;
	}
	
	/**
	 * 
	 * @param limitFileSize :"system.upload.minFileSize" or "system.upload.maxFileSize"
	 * @return
	 */
	public long getSize(String limitFileSize){
		String sSize=fileConfig.getProperty(limitFileSize).trim();
		 char unit=sSize.charAt(sSize.length()-1);
		 long size=Long.parseLong(sSize.substring(0, sSize.length()-1));
		 long lSize=0;
		 if(unit=='K'|unit=='k'){
			 lSize=size*1024;
		 }else if(unit=='M'|unit=='m'){
			 lSize=size*1024*1024;
		 }
		
		return lSize;
	}
	
	
	public static void main(String[] args) {
		File file=new File("d:/fileupload.properties");
		Properties config=new Properties();
		config.setProperty("system.upload.minFileSize", "0k");
		config.setProperty("system.upload.maxFileSize", "200k");
		ValidationResult result=new FileSizeValidationHandler(config).handle(file);
		System.out.println(result.getErrors().get(file.getName()));
	}

}
